package com.itluma.isWOak.realm;

import com.itluma.isWOak.pojo.AdminInfo;
import com.itluma.isWOak.pojo.FunctionInfo;
import com.itluma.isWOak.pojo.RoleInfo;
import com.itluma.isWOak.service.AdminInfoService;
import com.itluma.isWOak.service.AdminRoleService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author MS
 * @date 2021/4/1 16:54
 **/

public class MyRealm extends AuthorizingRealm{

    private Logger log = LoggerFactory.getLogger(MyRealm.class);

    private AdminInfoService adminInfoService;

    private AdminRoleService adminRoleService;


    public void setAdminService(AdminInfoService adminInfoService){
        this.adminInfoService = adminInfoService;
    }

   public void setAdminRoleService(AdminRoleService adminRoleService){
        this.adminRoleService = adminRoleService;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals){

        //1.获取角色
         AdminInfo admin = (AdminInfo) principals.getPrimaryPrincipal ();

        List<RoleInfo> roleInfos = adminRoleService.findByAdmin (admin);

        log.info ("认证的角色: " + roleInfos);


        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo ();

        info.addRoles (roleInfos.stream ().map (e -> e.getName ()).collect (Collectors.toList ()));

        //2.获取权限
        List<FunctionInfo> functionInfos = adminRoleService.findbyAdmin(admin);


        info.addStringPermissions (functionInfos.stream ().map (e -> e.getFunctionCode ()).collect (Collectors.toList ()));
        log.info ("获取的权限 : " + functionInfos);


        return info;
    }

    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException{

        if (token instanceof UsernamePasswordToken) {
            UsernamePasswordToken realToken = (UsernamePasswordToken) token;
            String username = realToken.getUsername ();

            log.info ("进入shiro认证拿到用户名: " + username);

            AdminInfo adminInfo = adminInfoService.getByAdminCode (username);
            if (adminInfo != null) {
                //返回信息给shiro认证
                return new SimpleAuthenticationInfo (adminInfo, adminInfo.getPassword (), ByteSource.Util.bytes (adminInfo.getAdminCode ()), getName ());
            }
        }
        return null;
    }
}